package cn.elead.it.sso.core.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.elead.it.sso.core.constant.GlobalVariable;
import cn.elead.it.sso.core.login.SsoTokenLoginHelper;
import cn.elead.it.sso.core.model.SsoResponse;
import cn.elead.it.sso.core.model.SsoUser;
import cn.elead.it.sso.core.path.AntPathMatcher;

/**
 * app sso filter
 *
 * @author luopeng
 */
@SuppressWarnings("serial")
public class SsoTokenFilter extends SsoFilter {
	private static Logger logger = LoggerFactory.getLogger(SsoTokenFilter.class);

	private static final AntPathMatcher antPathMatcher = new AntPathMatcher();

	// private String ssoServer;
	private String logoutPath;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

		// ssoServer = filterConfig.getInitParameter(GlobalVariable.SSO_SERVER);
		logoutPath = filterConfig.getInitParameter(GlobalVariable.SSO_LOGOUT_PATH);

		logger.info("SsoTokenFilter init.");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;

		// make url
		String servletPath = req.getServletPath();

		// excluded path check
		for (String excludedPath : excludedPaths) {
			String uriPattern = excludedPath.trim();

			// 支持ANT表达式
			if (antPathMatcher.match(uriPattern, servletPath)) {
				// excluded path, allow
				chain.doFilter(request, response);
				return;
			}

		}

		// logout filter
		if (logoutPath != null && logoutPath.trim().length() > 0 && logoutPath.equals(servletPath)) {
			// logout
			SsoTokenLoginHelper.logout(req);
			// response
			writeValueAsJson(resp, req, new SsoResponse().setStatus(200).setMsg("登出成功!"));
			return;
		}

		// login filter
		SsoUser ssoUser = SsoTokenLoginHelper.loginCheck(req);
		if (ssoUser == null) {
			// response
			writeValueAsJson(resp, req, new SsoResponse().setStatus(401).setMsg("sessionId已失效!"));
			return;
		}

		// ser sso user
		request.setAttribute(GlobalVariable.SSO_USER, ssoUser);
		request.setAttribute("API_UID", ssoUser.getUserId());

		// already login, allow
		chain.doFilter(request, response);
		return;
	}

}
